package netool

import (
	"github.com/go-netty/go-netty"
	"github.com/go-netty/go-netty/codec"
	"github.com/go-netty/go-netty/utils"
)


// PacketCodec create packet codec
func SelfPacketCodec(maxFrameLength int) codec.Codec {
	utils.AssertIf(maxFrameLength <= 0, "maxFrameLength must be a positive integer")
	return &packetCodec{maxFrameLength: maxFrameLength, buffer: make([]byte, maxFrameLength)}
}

type packetCodec struct {
	maxFrameLength int
	buffer         []byte
}

func (*packetCodec) CodecName() string {
	return "self-packet-codec"
}

func (p *packetCodec) HandleRead(ctx netty.InboundContext, message netty.Message) {

	reader := utils.MustToBytes(message)
	//n, err := reader.Read(p.buffer)
	//utils.AssertIf(nil != err && io.EOF != err, "%v", err)

	ctx.HandleRead(reader[p.maxFrameLength:])
}

func (*packetCodec) HandleWrite(ctx netty.OutboundContext, message netty.Message) {
	ctx.HandleWrite(message)
}

